package com.rimi.project.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.rimi.project.bean.User;
import com.rimi.project.dao.UserDao;
import com.rimi.project.dao.impl.UserDaoImpl;
import com.rimi.project.util.DESUtil;

/**
 * Servlet implementation class LoginCookieServlet
 */

// 不管链接长什么样都会进入LoginCookieServlet验证Cookie
@WebServlet("/")
public class LoginCookieServlet extends HttpServlet {

	private UserDao userDao = new UserDaoImpl();
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 验证用户Cookie是否有效
		
		// 从request里取出Cookie信息
		Cookie[] cookies = request.getCookies();
		
		String userName = "";
		String password = "";
		if (null != cookies) {
			for (Cookie cookie : cookies) {
//				if ("username".equals(cookie.getName())) {
//					// 找到cookie名字是username
//					userName = cookie.getValue();
//				} 
//				if ("password".equals(cookie.getName())) {
//					// 找到cookie名字是password
//					password = cookie.getValue();
//				}
				if ("token".equals(cookie.getName())) {
					// 获取cookie中token的值
					String token = cookie.getValue();
					// 对token进行解密
					String tmp = DESUtil.decode(token);
					// 拆分
					String[] arrays = tmp.split(",");
					
					if (null != arrays) {
						userName = arrays[0];
						password = arrays[1];
					}
				}
			}
		}
		
		// 验证cookie中用户名和密码是否有效
		User user = userDao.findUserByAccAndPassword(userName, password);
		if (null != user) {
			// 获取session对象
			HttpSession session = request.getSession();
			// 将username放入session对象
			session.setAttribute("username", user.getUsername());
			// 如果Cookie中的user是真实，跳转到主页
			request.getRequestDispatcher("/index.jsp").forward(request, response);
		} else {
			// 如果用户非法，强制用户登录
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

}
